import navToNext from '../../../wxjs/navToNext.js'
const app = getApp();

var data = {
  xhx_images: app.xhx_images,
  xhx_route: app.xhx_route,
  pageShow: false,
  challengeId: null,
  dialogValue: null,
  scheduleType: null,
  challengeType: [{
    type: '1',
    name: '日'
  }, {
    type: '2',
    name: '周'
  }, {
    type: '3',
    name: '月'
  }],
  timeTotal: {
    daysRound: '00',
    hoursRound: '00',
    minutesRound: '00',
    seconds: '00'
  },
  awardShow: 0,
  timeInterval: null,
  awardInterval: null,
  barWidth: 0,

  challengeData: null,

  isLogin: false,
};

var currentPage = {
  data,
  onLoad,
  onShow,
  getFont,
  setTime,
  setAward,
  awardScroll,
  cutAward,
  getDetail,
  cutType, //切换日周月的类型
  signUp,
  payment,
  getRunData,
  addUserKcal,
  getRewardRecord,
  receiveAward,
  goToOther,
  openDialog,
  onShareAppMessage: function() {
    const that = this;
    const challengeId = that.data.challengeId;
    return {
      title: '',
      path: `${app.xhx_route.challenge}?uuid=` + challengeId
    }
  },
  toPayPage(e){
    const that = this;
    // 判断用户登录
    var myInfo = app.isNavigateToLogin();
    if (!myInfo) return;
    myInfo = app.isNavigateToBind();
    if (!myInfo) return;
    const curItem = that.data.challengeData.matchScheduleInfo
    wx.navigateTo({
      url: '/pages/pay/pay?MatchType=1&item=' + JSON.stringify(curItem)
    })
  },
  onPullDownRefresh: function () {
    // wx.startPullDownRefresh();
    this.getRunData();
    wx.stopPullDownRefresh();
  },
  requestSubscribeMessage: function () {
    const that=this;
    wx.requestSubscribeMessage({
      tmplIds: ['PL7yUBWhTfLbqlML4DY314t-6ndp1vu6ZQsaP331FUA'],
      success(res) {
        console.log("success", res)
        const status = res['PL7yUBWhTfLbqlML4DY314t-6ndp1vu6ZQsaP331FUA'];
        if (status == 'accept') {
          app.middleware.requestAjax({
            serAddr: app.serAddrs.selfSetTemplateMsg,
            data: {
              matchId: that.data.challengeId || '',//打卡赛id
              matchType: 1,//打卡赛类型：1官方 2自定义
            },
            complete: function (res) {
              app.showToast(res.msg, 3000);
            }
          })
        }
      },
      fail(res) {
        console.log("fail", res)
      }
    })
  },
};

var page = Object.assign({}, navToNext, currentPage);

Page(page);

function onShow() {
  const that = this;
  if (that.data.rewardRecord && that.data.rewardRecord.status==0){
    that.getRewardRecord();
  }
  app.xlogin.getUser(function(res) {
    var myInfo = app.isNavigateToLogin();
    if (!myInfo) {
      that.setData({
        isLogin: false
      })
      return;
    }

    myInfo = app.isNavigateToBind();
    if (!myInfo) {
      that.setData({
        isLogin: false
      })
      return;
    }
    if (!that.data.isLogin) {
      that.getRunData();
      that.setData({
        isLogin: true
      })
    }
  })
}

function onLoad(options) {
  const that = this;
  // let userId;
  let challengeId = options && options.uuid || "";
  
  // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
  var scene = options && options.q && decodeURIComponent(options.q) || '';
  // console.log("【league】options======>", options);
  // console.log("【league】scene======>", scene);
  // 普通二维码进入怎么也得有10个字符
  if (scene.length > 10) {
    // 是否为json格式校验
    var tempScenes = scene.split("params=");
    if (tempScenes.length > 1) {
      tempScenes = tempScenes[1];
      var firstChar = tempScenes.charAt(0);
      var lastChar = tempScenes.charAt(tempScenes.length - 1);
      if (firstChar == "{" && lastChar == "}") {
        tempScenes = JSON.parse(tempScenes);
        // userId = tempScenes.userId;
        challengeId = tempScenes.uuid;
      }
    }
  }
  wx.showLoading({
    title: '加载中',
  })
  that.setData({
    challengeId: challengeId
  })
  // that.getRunData();
  // 获取字体
  that.getFont();
}

// 获取详情
function getDetail() {
  const that = this;
  var param = {};
  param.id = that.data.challengeId;

  // param.id = 16673
  // param.userId = 183
  param.scheduleType = that.data.scheduleType;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.getMatchDetail,
    data: param,
    // cancelToast: true,
    success: function(res) {
      wx.hideLoading();
      that.setData({
        challengeData: null
      })
      let temp = res.data;
      that.setData({
        awardShow: null,
        challengeData: temp,
        pageShow:true
      });
      if (temp.matchScheduleInfo.scheduleStatus == 2) {
        that.getRewardRecord();
      }
      that.setData({
        scheduleType: temp.matchScheduleInfo.scheduleType
      })
      // 进度条宽度
      if (temp.matchRule.targetType && temp.userStepKcakRecords) {
        for (var i = 0; i < temp.userStepKcakRecords.length; i++) {
          if (temp.matchRule.targetType == temp.userStepKcakRecords[i].recordType) {
            var targetCount = 0;
            if (temp.matchRule.targetType == 1) {
              targetCount = temp.matchRule.stepCount;
            } else {
              targetCount = temp.matchRule.kcal;
            }
            var width = ((temp.userStepKcakRecords[i].userRecord / targetCount) * 100);
            if (width > 100) {
              width = 100;
            }
            that.setData({
              barWidth: width
            });
          }
        }
      }
      var awardTotal = temp.matchScheduleInfo.bonusPool;
      if (awardTotal) {
        that.cutAward(true, '', awardTotal);
        if (awardTotal > 100) {
          that.awardScroll(2, 100, awardTotal);
        } else {
          that.awardScroll(1, 100, awardTotal);
        }
      }


      // 倒计时
      if (temp.matchScheduleInfo.scheduleStatus == 0) {
        that.setAward(temp.matchScheduleInfo.currentTimeStamp, temp.matchScheduleInfo.startTimeStamp);
      } else if (temp.matchScheduleInfo.scheduleStatus == 1) {
        that.setAward(temp.matchScheduleInfo.currentTimeStamp, temp.matchScheduleInfo.endTimeStamp);
      }

    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}

// 获取打开赛奖励信息
function getRewardRecord() {
  const that = this;
  var param = {
    tV2MatchScheduleId: that.data.challengeId
  };
  app.middleware.requestAjax({
    serAddr: app.serAddrs.getMatchRewardRecord,
    data: param,
    cancelToast: true,
    success: function(res) {
      console.log('===================',res);
      var data = res.data;
      that.setData({
        rewardRecord: data
      });
      if (!data) {
        return;
      }
      if (data.status == 0) {
        that.openDialog();
        // var dialogValue = null;
        // if (data.prizeType == 4) {
        //   dialogValue = {
        //     dialogShow: true,
        //     dialogType: 4, //领红包弹框
        //     bgImage: that.data.xhx_images.challengePopBg02, //背景大图片
        //     bgWidth: '370px', //背景图宽度
        //     bgHeight: '368px', //背景图高度
        //     title: '恭喜你完成' + data.matchSchuduleName,
        //     awardName: '快来抢红包吧！！！',
        //     btnName: '速度抢',
        //     confirm: function() { //点击按钮的回调
        //       that.receiveAward(data);
        //     },
        //   };
        // } else {
        //   dialogValue = {
        //     dialogShow: true,
        //     dialogType: 3, //领红包弹框
        //     bgImage: that.data.xhx_images.challengePopBg01, //背景大图片
        //     bgWidth: '370px', //背景图宽度
        //     bgHeight: '368px', //背景图高度
        //     title: '恭喜你获得' + data.matchSchuduleName,
        //     money: data.rewardAmount,
        //     awardName: data.prizeType == 1 ? '超级大奖' : data.prizeType == 2 ? '幸运大奖' : data.prizeType == 3 ? '优秀奖' : '现金',
        //     btnName: '分享领取',
        //     apply: '分享领取红包', //适用范围
        //     confirm: function() { //点击按钮的回调
        //       wx.navigateTo({
        //         url: that.data.xhx_route.posters + '?id=' + that.data.challengeId,
        //       })
        //     },
        //   };
        // }
        // that.setData({
        //   dialogValue: dialogValue,
        // })
      }
    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}

function openDialog(){
  const that=this;
  var data = that.data.rewardRecord;
  var dialogValue = null;
  if (data.prizeType == 4) {
    dialogValue = {
      dialogShow: true,
      dialogType: 4, //领红包弹框
      bgImage: that.data.xhx_images.challengePopBg02, //背景大图片
      bgWidth: '370px', //背景图宽度
      bgHeight: '368px', //背景图高度
      title: '恭喜你完成' + data.matchSchuduleName,
      awardName: '快来抢红包吧！！！',
      btnName: '速度抢',
      confirm: function () { //点击按钮的回调
        that.receiveAward(data);
        that.getRewardRecord();
      },
    };
  } else {
    dialogValue = {
      dialogShow: true,
      dialogType: 3, //领红包弹框
      bgImage: that.data.xhx_images.challengePopBg01, //背景大图片
      bgWidth: '370px', //背景图宽度
      bgHeight: '368px', //背景图高度
      title: '恭喜你获得' + data.matchSchuduleName,
      money: data.rewardAmount,
      awardName: data.prizeType == 1 ? '超级大奖' : data.prizeType == 2 ? '幸运大奖' : data.prizeType == 3 ? '优秀奖' : '现金',
      btnName: '分享领取',
      apply: '分享领取红包', //适用范围
      confirm: function () { //点击按钮的回调
        wx.navigateTo({
          url: that.data.xhx_route.posters + '?id=' + that.data.challengeId,
        })
      },
    };
  }
  that.setData({
    dialogValue: dialogValue,
  })
}

function receiveAward(awardData) {
  const that = this;
  var param = {
    id: awardData.id
  };
  app.middleware.requestAjax({
    serAddr: app.serAddrs.addMatchRewardRecord,
    data: param,
    cancelToast: true,
    success: function(res) {
      var dialogValue = {
        dialogShow: true,
        dialogType: 3, //领红包弹框
        bgImage: that.data.xhx_images.challengePopBg01, //背景大图片
        bgWidth: '370px', //背景图宽度
        bgHeight: '368px', //背景图高度
        title: '恭喜你完成' + awardData.matchSchuduleName,
        money: awardData.rewardAmount,
        awardName: awardData.prizeType == 1 ? '超级大奖' : awardData.prizeType == 2 ? '幸运大奖' : awardData.prizeType == 3 ? '优秀奖' : '现金',
        btnName: '立即分享',
        apply: '奖励已发放到你的钱包', //适用范围
        confirm: function() { //点击按钮的回调
          // console.log('==========================', that.data.xhx_route)
          wx.navigateTo({
            url: that.data.xhx_route.posters + '?id=' + that.data.challengeId,
          })
        },
      };
      that.setData({
        dialogValue: dialogValue
      })
    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}

// 支付
function signUp(e) {
  const that = this;
  var challengeId = e.target.dataset.id;
  let totalPrice = e.target.dataset.price || 0;
  if (totalPrice == 0 || !challengeId) return false;
  // 判断用户登录
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;
  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  var payParam = {};
  payParam.tV2MatchScheduleId = challengeId;
  payParam.wxMold = 1;

  app.middleware.requestAjax({
    serAddr: app.serAddrs.challengeByWXPay,
    data: payParam,
    cancelToast: true,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    success: function(ores) {
      that.payment(ores.data, challengeId);
    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "请求失败");
    }
  })
}

function payment(data, challengeId) {
  const that = this;
  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.prepayId,
    signType: data.signType,
    paySign: data.paySign,
    success(res) {
      that.getDetail();
    },
    fail(res) {
      app.middleware.showToast("支付失败");
    },
    complete: function(res) {

    }
  })
}

// 切换日周月
function cutType(e) {
  const that = this;
  var type = e.target.dataset.type;
  clearInterval(that.data.timeInterval);
  clearInterval(that.data.awardInterval);
  that.setData({
    scheduleType: type,
  })
  that.getDetail();
}
// 时间倒计时
function setTime(my_time) {
  var that = this;
  var days = my_time / 1000 / 60 / 60 / 24;
  var daysRound = Math.floor(days);
  var hours = my_time / 1000 / 60 / 60 - (24 * daysRound);
  var hoursRound = Math.floor(hours);
  var minutes = my_time / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
  var minutesRound = Math.floor(minutes);
  var seconds = my_time / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
  var time = {
    daysRound: daysRound,
    hoursRound: hoursRound,
    minutesRound: minutesRound,
    seconds: seconds
  }
  that.setData({
    timeTotal: time
  })
}

function setAward(curTime, startTime) {
  var that = this;
  var dateCur = curTime;
  var dateStart = startTime;
  // console.log(dateCur, '=================', dateStart)
  var my_time = dateStart - dateCur;
  // console.log('my_time=================', my_time)
  clearInterval(that.data.timeInterval);
  that.data.timeInterval = setInterval(function() {
    if (my_time == 0) {
      clearInterval(that.data.timeInterval);
    } else {
      my_time = my_time - 1000;
      that.setTime(my_time);
    }
  }, 1000);
}

// 奖金池滚动
function awardScroll(seconds, interval, moneyTotal) {
  var that = this;
  var award = moneyTotal;
  award = parseInt(award.toFixed(2) * 100);
  var awardShow = 0;
  seconds = seconds * 1000;
  var pre = award / (seconds / interval);
  if (pre <= 0.01) {
    return;
  } else {
    pre = Math.ceil(pre * 100) / 100;
  }
  clearInterval(that.data.awardInterval);
  that.data.awardInterval = setInterval(function() {
    if (seconds == 0) {
      clearInterval(that.data.awardInterval);
    } else {
      awardShow = awardShow + pre;
      if (awardShow + pre > award) {
        awardShow = award;
      }
      award = Math.ceil(award);
      that.cutAward(false, awardShow, award);
      seconds = seconds - interval;
    }
  }, interval);
}
// 切割奖金池
function cutAward(first, moneyList, award) {
  var that = this;
  var length = (award).toString().length;;
  if ((award.toString()).indexOf(".") != -1) {
    length = length - 1;
  }
  var awardShow = [];
  if (first) {
    if (award <= 0.01) {
      return;
    }

    for (let i = 0; i < length; i++) {
      awardShow[i] = 0;
    }
  } else {
    var moneyArr = (moneyList / 100).toFixed(2);
    moneyArr = moneyArr.split('');
    awardShow = moneyArr;
    var num = length - moneyArr.length;
    if (num > 0) {
      for (var i = 0; i < num; i++) {
        moneyArr.unshift(0);
      }
    }
  }
  // awardShow.splice(awardShow.length - 2, 0, '.');
  that.setData({
    awardShow: awardShow
  })
}

// 获取微信步数
function getRunData() {
  const that = this;
  wx.login({
    success(res) {
      if (res.code) {
        var code = res.code;
        wx.getWeRunData({
          success(res) {
            var param = {};
            param.wxCode = code;
            param.type = 3;
            param.iv = res.iv;
            param.encryptedData = res.encryptedData;
            that.addUserKcal(param);
          },
          fail: function(res) {
            app.middleware.showToast('授权失败,无法同步微信步数！');
            that.getDetail();
          }
        })
      } else {
        app.middleware.showToast('登录失败,无法同步微信步数！');
        that.getDetail();
      }
    }
  })
}

function addUserKcal(param) {
  const that = this;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.addUserKcal,
    data: param,
    cancelToast: true,
    success: function(res) {
      that.getDetail();
      // console.log('=================', res)
    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "加载失败");
      that.getDetail();
    }
  })
}

// 小程序跳转
function goToOther() {
  wx.navigateToMiniProgram({
    appId: 'wxf4469b3920bc1ed2',
    path: '/pages/data/base/base',
    // extraData: {
    //   foo: 'bar'
    // },
    // envVersion: 'develop',
    success(res) {
      // 打开成功
    }
  })
}


function getFont() {
  wx.loadFontFace({
    family: 'zihun35hao-jindianyahei',
    source: 'url("https://happyfit.oss-cn-shenzhen.aliyuncs.com/font.ttf")',
    success: function(res) {
      // console.log('======================', res.status)
    },
    fail: function(res) {
      // console.log('======================', res.status)
    },
    complete: function(res) {
      // console.log('======================', res.status);
    }
  });
}